package cn.myschool.web;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author oldliu
 * @since 1.0
 */
public class HelloServlet extends HttpServlet {
    public HelloServlet(){
        System.out.println("HelloServlet对象被创建了。。。");
    }

    @Override
    public void init() throws ServletException {
        System.out.println("HelloServlet 初始化了");
        ServletConfig config = super.getServletConfig();
        String user = config.getInitParameter("mysqluser");
        System.out.println("获得了配置参数："+user);
    }

    @Override
    public void destroy() {
        //super.destroy();
        System.out.println("java 78 HelloServlet被销毁了");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("关键的服务方法：请求方式："+req.getMethod());
        super.service(req, resp);//！！！！
        System.out.println("服务请求结束了。。。");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ip = req.getRemoteHost();
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>我的第一个servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>"+ip+",This is a get请求</h1>");
        out.println("</body>");
        out.println("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String ip = req.getRemoteHost();
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>我的第一个servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>"+ip+",This is a post 请求</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}
